<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" label-width="90px" ref="form">
      <el-row :gutter="24" class="addArticleItem">
        <el-col :span="8">
          <el-form-item label="文章标题" prop="title">
            <el-input placeholder="请输入文章标题" v-model="form.title"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章类型" prop="typeId">
            <el-select
              clearable
              placeholder="文章类型"
              v-model="form.typeId"
            >
              <el-option
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
                v-for="type in typeList"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="标签">
            <el-select
              :multiple-limit="5"
              allow-create
              default-first-option
              filterable
              multiple
              placeholder="标签"
              ref="tagSelect"
              v-model="form.tagArr"
            >
              <el-option
                :key="tag.id"
                :label="tag.tagName"
                :value="tag.id"
                v-for="tag in tagList"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="addArticleItem">
        <el-col :span="22">
          <el-form-item label="文章描述" prop="description">
            <el-input :row="3" placeholder="请输入文章描述" type="textarea" v-model="form.description"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="addArticleItem">
        <el-col :span="12">
          <el-form-item label="是否置顶" prop="isTop">
            <el-radio label="0" v-model="form.isTop">否</el-radio>
            <el-radio label="1" v-model="form.isTop">是</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否发布" prop="isRelease">
            <el-radio label="0" v-model="form.isRelease">否</el-radio>
            <el-radio label="1" v-model="form.isRelease">是</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="addArticleItem">
        <el-col :span="22">
          <el-form-item label="文章内容">
            <mavon-editor
              :toolbars="toolbars"
              @imgAdd="uploadImgMethod"
              ref="md"
              style="height: 450px"
              v-model="form.markerdownMessage"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="addArticleItem">
        <el-col :span="22">
          <el-form-item style="text-align:center">
            <el-button @click="submitForm" type="primary">确认</el-button>
            <el-button @click="resetQuery">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
  import { addArticle, getArticle, getToken, updateArticle } from '@/api/blog/article'
  import { tagList } from '@/api/blog/tag'
  import { typeList } from '@/api/blog/type'

  export default {
    name: 'add',
    data() {
      return {
        // 遮罩层
        loading: true,
        // 富文本编辑器工具栏
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          help: true, // 帮助
          redo: true, // 下一步
          undo: true, // 上一步
          trash: true, // 清空
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          subfield: true, // 单双栏模式
          preview: true // 预览
        },
        // 表单参数
        form: {
          id: '',
          title: '',
          typeId: '',
          tag: '',
          tagArr: [],
          tagList: [], // 新增的标签
          description: '',
          isTop: '0',
          isRelease: '1',
          markerdownMessage: '',
          deleted: '0',
          count: 0
        },
        // 表单校验
        rules: {
          title: [
            { required: true, message: '文章标题不能为空', trigger: 'blur' }
          ],
          typeId: [
            { required: true, message: '文章类型不能为空', trigger: 'blur' }
          ],
          tag: [
            { required: true, message: '文章标签不能为空', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '文章描述不能为空', trigger: 'blur' }
          ],
          markerdownMessage: [
            { required: true, message: '文章内容不能为空', trigger: 'blur' }
          ]
        },
        typeList: [],
        tagList: []
      }
    },
    mounted() {
      this.getTagList()
      this.getTypeList()
      if (this.$route.query.id) {
        this.getArticleById(this.$route.query.id)
      }
    },
    methods: {
      // 清空
      resetQuery() {
        this.resetForm('form')
        this.returnToThePreviousPage(false)
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            const tagList = []
            for (const tagItem of this.form.tagArr) {
              if (typeof tagItem === 'string') {
                const item = {
                  tagName: tagItem,
                  deleted: 0
                }
                tagList.push(item)
              }
            }
            this.form.tagList = tagList
            this.form.tagArr = this.form.tagArr.filter(res => {
              return typeof res === 'number'
            })
            this.form.tag = this.form.tagArr.toString()

            if (this.form.id != null && this.form.id !== '') {
              updateArticle(this.form).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess('修改成功')
                  this.returnToThePreviousPage(true)
                }
              })
            } else {
              addArticle(this.form).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess('新增成功')
                  this.returnToThePreviousPage(true)
                }
              })
            }
          }
        })
      },
      returnToThePreviousPage(check) {
        if (check) {
          const that = this
          setTimeout(function() {
            that.$router.back()
            that.closeSelectedTag(that.$route)
          }, 500)
        } else {
          this.$router.back()
          this.closeSelectedTag(this.$route)
        }
      },
      closeSelectedTag(view) {
        this.$tab.closePage(view).then(({ visitedViews }) => {
          this.toLastView(visitedViews, view)
        })
      },
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
          this.$tab.refreshPage(visitedViews)
        } else {
          if (view.name === 'Dashboard') {
            // to reload home page
            this.$router.replace({ path: '/redirect' + view.fullPath })
          } else {
            this.$router.push('/')
          }
        }
      },
      getArticleById(id) {
        getArticle(id).then(response => {
          this.form = response.data
        })
      },
      getTypeList() {
        typeList().then(res => {
          this.typeList = res.rows
        })
      },
      getTagList() {
        tagList().then(res => {
          this.tagList = res.rows
        })
      },
      // uploadImgMethod(pos, $file) {
      //   //新建form表单类型的数据
      //   let formData = new FormData();
      //   //将我们上传的图片地址$file加进表单里面，命名为“file”（参数名字与后端相匹配）
      //   formData.append("imgFile", $file)
      //   uploadImage(formData).then(res=> {
      //     // 将上传成功返回的路径+访问前缀，放回到md中图片的相应位置
      //     this.$refs.md.$img2Url(pos, process.env.VUE_APP_BASE_API + res.imgUrl)
      //   })
      // },
      uploadImgMethod(pos, $file) {
        getToken().then(res => {
          if (res.code === 200) {
            // 后台获取的token
            const token = res.token
            const prefix = res.prefix

            // 引入七牛云
            const qiniu = require('qiniu-js')

            // key官方说可以不传，但是会导致上传的文件的文件名是hash生成的，且没有文件后缀
            // 自定义的key一定要有文件后缀，不然文件没有后缀，而且必须保证key唯一，不然会被覆盖
            let date = new Date()
            let key = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + $file.lastModified + '-' + $file.name   //这是上船后返回的文件名，这里为了避免重复，加上了时间戳和随机数
            var config = {
              useCdnDomain: true,        //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
              region: qiniu.region.z0,      //选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域。  我这里是华东区
              domain: prefix, //配置好的七牛云域名  如   https://cdn.qniyun.com/
              chunkSize: 100,     //每个分片的大小，单位mb，默认值3
              forceDirect: true    //直传还是断点续传方式，true为直传
            }
            const observable = qiniu.upload($file, key, token, null, config)
            observable.subscribe({
              // next: (result) =>{
              //   console.log('next:',result)
              // },
              error: (error) => {
                console.log(error)
              },
              complete: (result) => {
                this.$refs.md.$img2Url(pos, prefix + '/' + result.key)
                console.log(result)
              }
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  .addArticleItem {
    margin-bottom: 8px;
    margin-left: 50px;
  }
</style>
